<template>
    <tableLayout :columns="columns" :page="false" :get="getData" :rowKey="Id" ref="layout" :selectItem="selectItem"
        :scroll="{ x: 'max-content' }" v-on:change="tableOnChange"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">
        <template v-slot:status="item">
            测试-{{ item.value.text.name }}
        </template>
        <template #button>
            <a-button type="primary" style="margin-left: 20px" @click='add'>新增</a-button>
            <a-button style="margin-left: 20px" @click="edit" :disabled="selectedRowKeys.length !== 1">修改</a-button>
            <a-button type="primary" style="margin-left: 20px" @click="del" :disabled="selectedRowKeys.length !== 1"
                danger>删除
            </a-button>
            <MenuToolBar>
                <template #button>
                    <a-button btnMark="Btn_osjgf34" type="primary" style="margin-left: 20px" @click='add'>新增</a-button>
                    <a-button style="margin-left: 20px" @click="edit"
                        :disabled="selectedRowKeys.length !== 1">修改</a-button>
                </template>
            </MenuToolBar>
        </template>

        <template #operationMore="item">
            <a @click="edit(null, item.value.record)">编辑</a>
            <a-divider type="vertical" />
            <a @click="del(null, item.value.record.Id)">删除</a>
        </template>
        <template v-slot:custom="data">
            <a-input v-model:value="data.formData[data.key]" />
        </template>
    </tableLayout>
    <a-modal :title="formState.Id ? '编辑菜单' : '新增菜单'" v-model:visible="model_visible" :confirm-loading="confirmLoading"
        @ok="model_handleOk" width="900px">
        <a-form ref="formRef" :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rules"
            layout="inline" class="comform">
            <a-form-item label="菜单类型" style="width: calc(50% - 20px);" class="form__item" name="MenuType">
                <a-radio-group v-model:value="formState.MenuType" button-style="solid">
                    <a-radio-button :value="1">菜单</a-radio-button>
                    <a-radio-button :value="2">按钮</a-radio-button>
                    <a-radio-button :value="3">链接按钮</a-radio-button>
                    <a-radio-button :value="4">自由按钮</a-radio-button>
                </a-radio-group>
            </a-form-item>
            <a-form-item v-if="formState.MenuType === 1" label="页面类型" style="width: calc(50% - 20px);"
                class="form__item" name="isNav">
                <a-radio-group v-model:value="isNav" button-style="solid" @change="navChange">
                    <a-radio-button :value="true">导航</a-radio-button>
                    <a-radio-button :value="false">页面</a-radio-button>
                </a-radio-group>
            </a-form-item>
            <a-form-item label="名称" style="width: calc(50% - 20px);" class="form__item" name="Name">
                <a-input v-model:value="formState.Name" />
            </a-form-item>
            <a-form-item v-if="formState.MenuType !== 3" label="图标" style="width: calc(50% - 20px);" class="form__item" name="Icon">
                <a-input v-model:value="formState.Icon">
                    <template #addonBefore>
                        <a-icon :type="formState.Icon" fill="white" />
                    </template>
                    <template #addonAfter>
                        <button @click="SetIcon" style="border:none;margin:0;padding:0;background:white;">
                            <setting-outlined />
                        </button>
                    </template>
                </a-input>
            </a-form-item>
            <a-form-item v-if="formState.MenuType === 1 && isNav === false" label="链接" style="width: calc(50% - 20px);"
                class="form__item" name="LinkUrl">
                <a-input v-model:value="formState.LinkUrl" />
            </a-form-item>

            <a-form-item v-if="formState.MenuType !== 1" label="按钮方法" style="width: calc(50% - 20px);"
                class="form__item" name="BtnMethod">
                <a-input v-model:value="formState.BtnMethod" />
            </a-form-item>
            <a-form-item v-if="formState.MenuType !== 1 && formState.MenuType !== 3" label="按钮类型" style="width: calc(50% - 20px);"
                class="form__item" name="BtnType">
                <a-radio-group v-model:value="formState.BtnType" size="small" button-style="solid" style="width:100%;">
                    <a-radio-button value="primary" primary>Primary</a-radio-button>
                    <a-radio-button value="default">Default</a-radio-button>
                    <a-radio-button value="dashed">Dashed</a-radio-button>
                    <a-radio-button value="text">Text</a-radio-button>
                    <a-radio-button value="link">Link</a-radio-button>
                </a-radio-group>
            </a-form-item>

            <a-form-item v-if="formState.MenuType !== 1" label="按钮标识" style="width: calc(50% - 20px);"
                class="form__item" name="BtnMark">
                <a-input v-model:value="formState.BtnMark" :readonly="true">
                    <template #suffix>
                        <a-tooltip title="复制按钮标识">
                            <CopyTwoTone style="color: rgba(0, 0, 0, 0.45)" @click="onCopyFormCode" />
                        </a-tooltip>
                    </template>
                </a-input>
            </a-form-item>

            <a-form-item v-if="formState.MenuType !== 1 && formState.MenuType !== 3" label="单选" style="width: calc(50% - 20px);"
                class="form__item" name="SingleSelected">
                <a-switch v-model:checked="formState.SingleSelected" />
            </a-form-item>
            <!-- <a-form-item v-if="formState.MenuType === 1" label="组件" style="width: calc(50% - 20px);" class="form__item" name="Component">
                <a-input v-model:value="formState.Component" />
            </a-form-item> -->
            <a-form-item label="排序" style="width: calc(50% - 20px);" class="form__item" name="SortId">
                <a-input v-model:value="formState.SortId" />
            </a-form-item>
            <!-- <a-form-item v-if="formState.MenuType === 1" label="键" style="width: calc(50% - 20px);" class="form__item" name="Key">
                <a-input v-model:value="formState.Key" />
            </a-form-item> -->
            <a-form-item label="上级菜单" style="width: calc(50% - 20px);" class="form__item" name="ParentId">
                <a-tree-select v-model:value="formState.ParentId" style="width: 100%"
                    :replaceFields="{ children: 'children', title: 'Name', key: 'Id', value: 'Id' }"
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :tree-data="treeData"
                    placeholder="Please select" tree-default-expand-all />
            </a-form-item>
            <!-- <a-form-item v-if="formState.MenuType === 1" label="保持打开" style="width: calc(50% - 20px);" class="form__item" name="KeepAlive">
                <a-checkbox v-model:checked="formState.KeepAlive">
                </a-checkbox>
            </a-form-item> -->
            <a-form-item label="状态" style="width: calc(50% - 20px);" class="form__item" name="State">
                <a-radio-group name="radioGroup" v-model:value="formState.State">
                    <a-radio :value="1">启用</a-radio>
                    <a-radio :value="0">停用</a-radio>
                </a-radio-group>
            </a-form-item>
            <a-form-item v-if="formState.MenuType !== 1" label="按钮属性" style="width: calc(100% - 20px);"
                class="form__item" name="BtnAttr" :labelCol="{ span: 3 }" :wrapperCol="{ span: 21 }">
                <a-textarea v-model:value="formState.BtnAttr" placeholder="按钮属性" :rows="2" />
            </a-form-item>
            <a-form-item v-if="formState.MenuType !== 1" label="按钮样式" style="width: calc(100% - 20px);"
                class="form__item" name="BtnStyle" :labelCol="{ span: 3 }" :wrapperCol="{ span: 21 }">
                <a-textarea v-model:value="formState.BtnStyle" placeholder="按钮样式" :rows="4" />
            </a-form-item>

        </a-form>
    </a-modal>

    <a-modal title="选择图标" v-model:visible="model_icon_visible" :confirm-loading="confirmLoading" width="800px"
        @ok="model_icon_handleOk">
        <!-- 新增显示当前选中图标的区域 -->
        <div class="selected-icon-tip">
            当前选中图标：
            <a-icon :type="selectedIcon" fill="white" />
            <span style="margin-left: 8px;">{{ selectedIcon }}</span>
        </div>

        <div class="icon__container" style="height:600px !important;overflow:auto;">

            <ul class="icons">
                <!-- 使用 v-for 遍历图标名称列表 -->
                <li v-for="iconName in iconNames" :key="iconName">
                    <a-tooltip :title="iconName">
                        <a-icon :type="iconName" :class="{ 'icon-selected': selectedIcon === iconName }"
                            @click="selectIcon(iconName)" />
                    </a-tooltip>
                </li>
            </ul>
        </div>
    </a-modal>
</template>

<script lang="ts">
import { provide, defineComponent, defineExpose, ref, onMounted, onBeforeMount, nextTick, UnwrapRef, reactive, h, VNode } from 'vue';
import tableLayout from '@/components/tableLayout/tableLayout.vue';
import { getData, delMenu, setMenu } from '@/api/syssetting/menu';
import { MenuInput } from '@/types/api/syssetting/menu';
import { Layout, message, Tag } from 'ant-design-vue';
import aIcon from '@/components/aicon/aicon.vue';
import { SettingOutlined, CopyTwoTone } from '@ant-design/icons-vue';
import * as antIcons from '@ant-design/icons-vue';
import { v4 as uuidv4 } from 'uuid';
import { CustomIdPrefix } from '@/components/id/idGenerater';
import MenuToolBar from '@/components/toolbar/menuToolBar.vue';

export default defineComponent({
    name: 'sys_menu',
    components: {
        tableLayout,
        SettingOutlined,
        aIcon,
        CopyTwoTone,
        Tag,
        MenuToolBar
    },
    setup() {
        const layout = ref();
        const Id = ref<string>();
        const isNav = ref<boolean>(true);

        onBeforeMount(() => {
            Id.value = "Id";
            getData({ MenuType: 1 }).then(e => {
                treeData.value = e.data.Data;
            }).catch(err => {
                message.error(err.message || "获取菜单列表失败!")
            })
        })

        const Test = () => {
            alert("测试")
        }
        provide('parentMethods', { Test: Test });
        //列表
        const columns = [
            { title: '菜单名称', dataIndex: 'Name' },
            {
                title: '类型',
                dataIndex: 'MenuType',
                customRender: function ({ text }): VNode { return h(Tag, { color: (text === 1 ? 'pink' : text === 2 ? 'green' : text === 3 ? 'blue' : 'orange') }, text === 1 ? "菜单" : text === 2 ? "按钮" : text === 3 ? "快捷操作" : "自由按钮"); }
            },
            {
                title: '图标', dataIndex: 'Icon', customRender: function ({ text }): VNode { return h(aIcon, { type: text }); }
            },
            { title: '链接', dataIndex: 'LinkUrl' },
            { title: '排序', dataIndex: 'SortId' },
            {
                title: '状态', dataIndex: 'State', customRender: function ({ text }): VNode {
                    return h('div', {
                        style: {
                            color: 'red'
                        }
                    }, text ? '有效' : '无效');
                }
            }
        ]

        // 筛选
        const selectItem = ref([
            { title: '菜单名称', key: 'Name', type: 'input', itemWidth: '290px' },
            { title: '键', key: 'Key', type: 'input', itemWidth: '290px' },
            { title: '组件', key: 'Component', type: 'input', itemWidth: '290px' },
        ])

        // 规则
        const rules = {
            Name: [{ required: true, message: '请输入名称', trigger: 'change' }],
            Key: [{ required: true, message: '请输入键', trigger: 'change' }],
            LinkUrl: [{ required: true, message: '请输入链接', trigger: 'change' }],
            Redirect: [{ required: true, message: '请输入重定向', trigger: 'change' }],
            Component: [{ required: true, message: '请输入组件', trigger: 'change' }]
        }
        const treeData = ref([]);

        const tableOnChange = (e: any) => {
            let dataSource = layout.value.dataSource;
            treeData.value = dataSource;
        }

        //表单对象
        const formState: UnwrapRef<MenuInput> = reactive({
            Id: 0,
            PlatformId: 0,
            ParentId: 0,
            Name: '',
            Icon: '',
            LinkUrl: '',
            SortId: 0,
            State: 0,
            Redirect: '',
            Key: '',
            Component: '',
            KeepAlive: false,
            MenuType: 1,
            BtnMark: '',
            BtnMethod: '',
            BtnType: '',
            BtnStyle: '',
            BtnAttr: '',
            SingleSelected: false
        });

        //复制表单编码
        const onCopyFormCode = async (event: any) => {
            try {
                await navigator.clipboard.writeText(formState.BtnMark);
                message.success('复制成功！');
            } catch (err) {
                console.error('复制失败', err);
                message.error('复制失败，请手动复制');
            }
        }

        const add = () => {
            let btnCode = CustomIdPrefix("Btn");
            model_visible.value = true;
            Object.assign(formState, {
                Id: 0,
                PlatformId: 0,
                ParentId: selectedRowKeys.value.length>0? selectedRowKeys.value[0] : 0,
                Name: '',
                Icon: '',
                LinkUrl: '',
                SortId: 0,
                State: 0,
                Redirect: '',
                Key: uuidv4(),
                Component: '',
                KeepAlive: false,
                BtnMark: btnCode,
                BtnMethod: '',
                BtnType: '',
                BtnStyle: '',
                BtnAttr: '',
                SingleSelected: false
            });
        }

        const navChange = () => {
            formState.Component = isNav.value ? formState.LinkUrl : '';
            formState.LinkUrl = isNav.value ? '' : formState.LinkUrl;
        }

        const edit = (event: any, item: any) => {
            let selectItem = item;
            if (!item) {
                if (!selectedRowKeys.value || selectedRowKeys.value.length <= 0 || selectedRowKeys.value.length > 1) {
                    message.warning('请先选择一条数据!');
                    return;
                }
                selectItem = selectedRows.value[0];
            }
            model_visible.value = true;
            debugger
            isNav.value = !(selectItem.LinkUrl !== '' && selectItem.LinkUrl !== undefined);
            Object.assign(formState, selectItem);
        }



        const del = (event: any, Id: any) => {
            let selectId = Id;
            if (!selectId) {
                if (!selectedRowKeys.value || selectedRowKeys.value.length <= 0 || selectedRowKeys.value.length > 1) {
                    message.warning('请先选择一条数据!');
                    return;
                }
                selectId = selectedRows.value[0].Id;
            }

            delMenu({ Id: selectId }).then(() => {
                message.success("删除成功!");
                layout.value.getData();
            }).catch(err => {
                message.error(err.message || "删除失败!")
                confirmLoading.value = false;
            })
        }

        const model_visible = ref<boolean>(false);
        const confirmLoading = ref<boolean>(false);
        const formRef = ref()

        const model_handleOk = () => {
            formRef.value.validate().then(() => {
                confirmLoading.value = true;
                if (formState.MenuType == 1) {
                    formState.Component = formState.LinkUrl;
                    formState.BtnMark = '';
                } else {
                    formState.LinkUrl = formState.Component = '';
                }

                setMenu(formState).then(e => {
                    if (formState.Id == 0) {
                        message.success("添加成功！");
                    } else {
                        message.success("修改成功！");
                    }

                    confirmLoading.value = false;
                    model_visible.value = false;
                    debugger
                    layout.value.getData();
                }).catch(err => {
                    message.error(err.message || "添加失败!")
                    confirmLoading.value = false;
                })
            }).catch(() => {
                message.error('请检查必填项是否全部填写!');
            })
        }

        /****************************************选择图标***********************************/
        const model_icon_visible = ref<boolean>(false);
        const iconNames = ref(Object.keys(antIcons).filter(key => key !== 'default' && key !== 'createFromIconfontCN' && key !== 'getTwoToneColor'))
        const selectedIcon = ref(''); // 记录选中的图标名称

        const SetIcon = () => {
            model_icon_visible.value = true;
        }

        const selectIcon = (iconName: string) => {
            selectedIcon.value = iconName;
        }

        const model_icon_handleOk = () => {
            formState.Icon = selectedIcon.value; // 更新表单中的图标名称
            model_icon_visible.value = false; // 关闭模态框 
        }

        /****************************************选择图标***********************************/


        // 多选
        const selectedRowKeys = ref<any[]>([]);
        const selectedRows = ref<any[]>([]);
        const onSelectChange = (keys: [], rows: any) => {
            selectedRowKeys.value = keys;
            selectedRows.value = rows;
        }


        const labelCol = { span: 6 };
        const wrapperCol = { span: 18 };


        return {
            columns, getData, selectItem, Id, add, edit, del, model_visible, confirmLoading,
            formRef, model_handleOk, labelCol, wrapperCol, rules, formState, selectedRowKeys, selectedRows,
            onSelectChange, tableOnChange, treeData, SetIcon, iconNames, model_icon_visible, selectIcon, selectedIcon,
            model_icon_handleOk, layout, isNav, navChange, onCopyFormCode, Test
        }
    }
})
</script>

<style lang="scss" scoped>
.comform {
    & .form__item {
        margin-bottom: 16px;

        & .ant-form-item-label {
            flex-grow: 1 !important;
            flex-shrink: 0;
        }
    }
}

.icon__container {
    padding: 20px;

    & .tip {
        font-size: 14px;
        font-weight: bold;
    }

    & pre {
        background-color: #f6f6f6;
        padding: 10px
    }

    & .icons {
        display: flex;
        flex-wrap: wrap;
        margin: 0;
        padding: 0;

        & li {
            margin-right: 10px;
            list-style: none;
            font-size: 24px;
            cursor: pointer;
        }
    }
}

// 定义选中效果的样式
.icon-selected {
    color: red; // 选中时的颜色
    transform: scale(1.2); // 选中时放大 1.2 倍
    transition: all 0.2s ease; // 添加过渡效果
}

.selected-icon-tip {
    padding: 12px;
    background-color: #f0f2f5;
    border-radius: 4px;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    font-size: 24px;
}
</style>
<style lang="scss">
.comform {
    & .form__item {
        margin-bottom: 16px;

        & .ant-form-item-label {
            flex-grow: 1;
            flex-shrink: 0;
        }
    }
}

.icon__container {
    padding: 20px;

    & .tip {
        font-size: 14px;
        font-weight: bold;
    }

    & pre {
        background-color: #f6f6f6;
        padding: 10px
    }

    & .icons {
        display: flex;
        flex-wrap: wrap;
        margin: 0;
        padding: 0;

        & li {
            margin-right: 10px;
            list-style: none;
            font-size: 24px;
            cursor: pointer;

            &:hover {
                color: #007bff; // 鼠标悬停时的颜色 
            }
        }
    }
}

// 定义选中效果的样式
.icon-selected {
    color: red; // 选中时的颜色
    transform: scale(1.2); // 选中时放大 1.2 倍
    transition: all 0.2s ease; // 添加过渡效果
}

.selected-icon-tip {
    padding: 12px;
    background-color: #f0f2f5;
    border-radius: 4px;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    font-size: 16px;
}
</style>